#include "tcp.server.h"

//#define PORT 1111
int create_tcp_server(char *ip, int port)
{
    int sockfd;
    int opt = 1;

    signal(SIGPIPE, SIG_IGN);

    struct sockaddr_in s_addr;

    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
    {
        perror("sockfd error!");
        goto err;
    }
    printf("socket successfully!\n");

    s_addr.sin_family = AF_INET;
    s_addr.sin_port = htons(port);
    s_addr.sin_addr.s_addr = inet_addr(ip);

    setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));

    if (bind(sockfd, (struct sockaddr *)&s_addr, sizeof(struct sockaddr_in)) == -1)
    {
        perror("bind error!");
        goto err;
    }

    printf("bind successfully!\n");

    if (listen(sockfd, 20) == -1)
    {
        perror("listen error!");
        goto err;
    }
    printf("listen successfully!\n");

    return sockfd;
err:
    return -1;
}

void set_nonblock(int fd)
{
    // int flag;
    // flag = fcntl(fd, F_GETFL);
    // flag = flag | SOCK_NONBLOCK;
    // fcntl(fd, F_GETFL, flag);  
    fcntl(fd, F_GETFL, SOCK_NONBLOCK);   
}